package cn.itcast.bos.web.action.base;


import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.struts2.ServletActionContext;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Actions;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.ParentPackage;
import org.apache.struts2.convention.annotation.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Controller;

import cn.itcast.bos.domain.base.Standard;
import cn.itcast.bos.service.base.StandardService;

import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.ModelDriven;
import com.opensymphony.xwork2.util.ValueStack;

@Controller
@Namespace("/")
@ParentPackage("json-default")
@Scope("prototype")
@Actions
public class StandardAction extends ActionSupport implements ModelDriven<Standard> {

	
	private static final long serialVersionUID = 1L;
	
	@Autowired
	private StandardService standardService;
	
	private Standard standard = new Standard();

	@Override
	public Standard getModel() {
		return standard;
	}
	
	@Action(value="standard_save",results={@Result(name="success",type="redirect",location="./pages/base/standard.html")})
	public String save() {
		System.out.println("存储成功......");
		standardService.save(standard);
		return SUCCESS;
	}
	
	//设置属性驱动
	private int page;
	private int rows;
	
	public void setPage(int page) {
		this.page = page;
	}

	public void setRows(int rows) {
		this.rows = rows;
	}

	//数据查询
	@Action(value="standard_query",results={@Result(name="success",type="json")})
	public String query() {
		Pageable pageable = new PageRequest(page-1,rows);
		Page<Standard> data = standardService.findPageData(pageable);
		
		//存入map集合
		Map<String,Object> map = new HashMap<String,Object>();
		map.put("total", data.getTotalElements());
		map.put("rows", data.getContent());
		ValueStack valueStack = (ValueStack) ServletActionContext.getRequest().getAttribute(ServletActionContext.STRUTS_VALUESTACK_KEY);
		valueStack.push(map);	
		return SUCCESS;
	}
	
	//查询取件标准类型
	@Action(value="standard_findtype",results={@Result(name="success",type="json")})
	public String findType() {
		List<Standard> standards = standardService.findAll();
		ValueStack valueStack = ActionContext.getContext().getValueStack();
		valueStack.push(standards);
		return SUCCESS;
	}

}
